// pagesProperty/pages/oa/examine/reg/index.js
var app = getApp(), fetchApi = require("../../../../../utils/httpPost.js"), 
common_Js = require("../../../../../component/common.js");

import Dialog from '../../../../../component/vant/dialog/dialog';
import Toast from '../../../../../component/vant/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    approveId:0,
    submitState:false,
    fileList0:[],
    regRecord:{
      approveId:0,//申请类目id
      // approveTitle:'',//标题
      approveType:0,//费用类型
      // userId:'',//申请人 userid
      userName:'',//申请人姓名
      // deptName:'',//小区/物业/公司名称/部门名称
      settlementMoney:'',//结算金额/清算金额
      useDate:'',
      state:0,//状态 0 - 未处理
      // checkResult:'',  //审核结果
      introduce:'',
      remark:'',
    },
    regInfo:{
      goodName:'',
      count:'',
      singlePrice:'',
      totalPrice:'',
      remark:'',//备注信息
    },
    regInfoCount:0,
    regInfos:[],
    isShowPopup:false,
    currentDate:new Date(),
    minDate: new Date(2022,0,1).getTime(),
    recordId:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('options',options)
    if(options.aid){
      this.data.approveId = parseInt(options.aid)
      this.data.regRecord.approveId = parseInt(options.aid);
    }
    if(options.type){
      this.data.regRecord.approveType = parseInt(options.type);
    }
    //修改，根据现有id 获取当前申请记录
    if(options.id){
      this.data.recordId =  parseInt(options.id);
      console.log('recordId', this.data.recordId)
      this.onHttpInitDetail();
    }
    this.setData({
      regRecord: this.data.regRecord
    })
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/examine/approve/list', {
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex
    }, function (res) {
      that.data.isNewReq = 0;
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex += 1;
          console.log("审批类目列表", res)
          var approves = res.data.data.approves;
          if(approves.length > 0){
            for (var index in approves) {
              that.data.approveList.splice(that.data.approveList.length, 0, approves[index]);
            }
            that.setData({
              hasData: true,
              approveList: that.data.approveList
            })
          }
        }
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  
  /**
   * 获取页面数据的 http请求
   */
  onHttpInitDetail: function () {
    var that = this;
    fetchApi.httpPost('/examine/approve/record/detail', {
      record_id: that.data.recordId,
    }, function (res) {
      if (res.data.code == 0) {
        that.data.regInfos = res.data.data.record.regInfos
        that.setData({
          hasData: true,
          regRecord: res.data.data.record,
          regInfos: res.data.data.record.regInfos,
        })
        let regImgs = res.data.data.record.regImgs;
        if(regImgs.length > 0){
          that.data.fileList0 = [];
          for(let img of res.data.data.record.regImgs){
            let imgTemp = {
              tempFilePath: img.imgUrl,
              thumb: img.imgUrl,
              url: img.imgUrl,
            }
            that.data.fileList0.push(imgTemp)
          }
          that.setData({
            fileList0: that.data.fileList0
          })
        }
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  addReginfo(e){
    var regInfo = {
      approveRecordId:0,
      goodName:'',
      count:'',
      singlePrice:'',
      totalPrice:'',
      specs:'',
      requirementInfo:'',//要求信息
      remark:'',//备注信息
    };
    this.data.regInfos.push(regInfo);

    this.setData({
      regInfos: this.data.regInfos,
    })
  },
  clearChoose(e){
    console.log('clearChoose', e)
    var index = e.currentTarget.dataset.index;
    this.data.regInfos.splice(index, 1);
    this.setData({
      regInfos: this.data.regInfos
    })
  },
  inputHandleRegRecord(e){
    console.log('inputHandleRegRecord',e);
    var key = e.currentTarget.dataset.key;
    if(key == 'settlement'){
      this.data.regRecord.settlementMoney = e.detail;
    } else if(key == 'introduce'){
      this.data.regRecord.introduce = e.detail;
    } else if(key == 'user_name'){
      this.data.regRecord.userName = e.detail;
    } else if(key == 'remark'){
      this.data.regRecord.remark = e.detail;
    }
  },
  inputHandleRegInfo(e){
    console.log('inputHandleRegInfo',e);
    var index = e.currentTarget.dataset.index;
    var key = e.currentTarget.dataset.key;
    if(key == 'name'){
      this.data.regInfos[index].goodName = e.detail;
    } else if(key == 'count'){
      this.data.regInfos[index].count = e.detail;
    } else if(key == 'single'){
      this.data.regInfos[index].singlePrice = e.detail;
    } else if(key == 'total'){
      this.data.regInfos[index].totalPrice = e.detail;
    } else if(key == 'remark'){
      this.data.regInfos[index].remark = e.detail;
    }
  },
  onClickTimeView(e){
    console.log('onCancelDate',e)
    this.setData({
      isShowPopup:!this.data.isShowPopup
    })
  },
  onConfirmDate(e){
    console.log('onConfirmDate',e)
    var time = new Date(e.detail);
    var month = time.getMonth() + 1;
    var nowDate = time.getDate();
    var date = (nowDate < 10 ? '0' + nowDate : nowDate )
    date = time.getFullYear() + '-' + (month < 10 ? '0' + month : month ) + '-' + date;
    this.data.regRecord.useDate = date;
    console.log('date',date)
    this.setData({
      regRecord: this.data.regRecord,
      isShowPopup:!this.data.isShowPopup,
    })    
  },
  onChangeDatePicker(e){
    var type = e.currentTarget.dataset.type;
    this.setData({
      isShowPopup: !this.data.isShowPopup,
    })
    
    if(type == 'begin'){
      this.data.dateType = 0;
      var arrDate = this.data.beginMonth.split("-");
      var time = new Date(arrDate[0],parseInt(arrDate[1]) - 1,1).getTime();
      var date = new Date(arrDate[0],parseInt(arrDate[1]) - 1,1);

      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      this.data.beginMonth = year + ' -' + (month >= 10 ? month :'0' + month);
      this.setData({
        currentDate: time
      })

    }else{
      this.data.dateType = 1;
      var arrDate = this.data.endMonth.split("-");
      var time = new Date(arrDate[0],parseInt(arrDate[1]) - 1,1).getTime();
      var date = new Date(arrDate[0],parseInt(arrDate[1]) - 1,1);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      this.data.endMonth = year + ' -' + (month >= 10 ? month :'0' + month);
      this.setData({
        currentDate: time
      })
    }
    console.log('this.data.beginMonth',this.data.beginMonth);
    console.log('this.data.endMonth',this.data.endMonth);

    
    // this.onHttpInit();
  },
  submitOp:function(e){
    console.log('this.data.regRecord',this.data.regRecord)
    console.log('this.data.regInfos',this.data.regInfos);

    var that = this;
    
    if(that.data.regRecord.introduce == '' || that.data.regRecord.introduce == undefined){
      Toast("请输入申请事由");
      return ;
    }

    if(that.data.regRecord.settlementMoney == '' || that.data.regRecord.settlementMoney == 0 
      || that.data.regRecord.settlementMoney == undefined){
      
      if(that.data.regRecord.approveType == 0){
        Toast("请输入报销金额");
      }else{
        Toast("请输入采购金额");
      }
      return ;
    }
    if(that.data.regRecord.useDate == '' || that.data.regRecord.useDate == undefined){
      Toast("请输入费用发生日期");
      return ;
    }

    if(that.data.regRecord.userName == '' || that.data.regRecord.userName == undefined){
      Toast("请输入申请人");
      return ;
    }

    if(that.data.regRecord.approveType == 1 && that.data.regInfos.length == 0){
      Toast("请添加明细");
      return ;
    }

    for(var index in that.data.regInfos){
      if(that.data.regInfos[index].goodName == ''){
        Toast("请输入名称");
        return ;
      } else if(that.data.regInfos[index].count == '' || that.data.regInfos[index].count == 0){
        Toast("请输入物品数量");
        return ;
      } else if(that.data.regInfos[index].singlePrice == '' || that.data.regInfos[index].singlePrice == 0){
        Toast("请输入物品单价");
        return ;
      }
    }

    that.setData({ submitting : true})
    let url = '/examine/approve/add/record';
    console.log('recordId   2222', that.data.recordId)
    if(that.data.recordId > 0){
      console.log('recordId 1111', that.data.recordId)
      that.data.regRecord.id = that.data.recordId;
      that.data.approveId = that.data.regRecord.approveId;
      url = '/examine/approve/update/record';
    }
    fetchApi.httpPost(url, {
      record_id: that.data.recordId,
      approve_id: that.data.approveId,
      reg_record: that.data.regRecord,
      reg_info: that.data.regInfos,
    }, function (res) {
      console.log('res', res)
      if (res.data.code == 0) {
        var record_id = res.data.data;
        if (record_id > 0 && that.data.fileList0.length > 0) {
          for (var index in that.data.fileList0) {
            wx.uploadFile({
              url: fetchApi.getPlatformUrl() + '/examine/approve/uploadImg',
              filePath: that.data.fileList0[index].url,
              name: 'file',
              formData: { record_id: record_id,sort:index, type : 0 },
              success: function (res) {
                console.log('uploadFile success res', res)
              }, fail: function (res) {
                console.log('uploadFile fail res', res)
              }
            })
          }
        }

        Toast.success(res.data.msg);
        setTimeout(function(){
          // wx.switchTab({
          //   url: '/pages/home/home',
          // })
          wx.navigateTo({
            url: '../record/index',
          })
        },1000)

      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  deleteImg0:function(res){
    console.log('删除图片',res)
    this.data.fileList0 = []
    this.setData({
      fileList0:[]
    })
  },
  afterRead(event) {
    console.log('afterRead',event)
    const { file, name } = event.detail;
    console.log('afterRead name',name)
    console.log('afterRead file',file)
    const fileList = this.data[`fileList${name}`];
    this.setData({ [`fileList${name}`]: fileList.concat(file) });
    console.log('afterRead fileList',fileList)
    if(name == 0){
      this.data.fileList0.concat(file)
      console.log('fileList0',this.data.fileList0)
    }
  },
  oversize() {
    wx.showToast({ title: '文件超出大小限制', icon: 'none' });
  },
})